import Vue from 'vue'
import router, { resetRouter } from './router'
import store from './store'
import { MessageBox } from 'element-ui'

import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { openNotification } from '@/utils/util'

// 根级菜单
const rootRouter = {
  key: '',
  name: 'index',
  path: '',
  component: 'BasicLayout',
  redirect: '/assets',
  meta: {
    title: '首页'
  },
  children: []
}

let confirmFlag = false

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  path: '*', redirect: '/404', hidden: true
}

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', 'register', 'registerResult', 'recover', 'recoverResult'] // no redirect whitelist
const defaultRoutePath = '/'
router.beforeEach(async (to, from, next) => {

  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`))
  const token = store.getters.token || Vue.ls.get(ACCESS_TOKEN)
  if (to.path == '/satisfaction/satisfaction-startTest') { // 当进入这个页面进行记录
    confirmFlag = true; // 改变信号
    next();
  } else {
    if (confirmFlag) { // 如果路由发生变化判断信号
      Vue.prototype.$confirm({
        title: '确认所有项目已考评完成，点击确定退出此页面?',
        onOk() {
          next()
          confirmFlag = false;
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
      next(false)
      return false
    } else {
      next()
    }
  }
  if (token) {
    /* has token */
    if (to.path === '/user/login') {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      // console.log('router=============', store.getters.addRouters)
      if (store.getters.addRouters && store.getters.addRouters.length) {
        next()
      }
      else {
        await store.dispatch('getLocalUserInfo')
        // const asyncRouterMap = await store.dispatch('GenerateRoutes')
        // router.addRoutes(asyncRouterMap)
        // next()
        next({ ...to, replace: true })
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/user/login', query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})